// 实时交易量监控页面主逻辑

/**
 * 实时交易量监控应用主类
 */
class TransactionMonitorApp {
    constructor() {
        this.config = {
            refreshIntervals: {
                transaction: 60 * 1000,     // 交易量：1分钟
                failCode: 60 * 1000         // 失败码：1分钟
            },
            apiEndpoints: {
                transaction: '/api/tranvolume/transaction/realtime',
                failCode: '/api/tranvolume/fail-code/trend'
            }
        };
        
        this.timers = {};
        this.mockData = this.initMockData();
        this.isUsingMockData = true;
        
        this.init();
    }

    /**
     * 初始化应用
     */
    async init() {
        try {
            showLoading(true);
            
            // 初始化时间显示
            this.initTimeDisplay();
            
            // 初始化事件监听
            this.initEventListeners();
            
            // 检查API可用性
            await this.checkApiAvailability();
            
            // 加载初始数据
            await this.loadAllData();
            
            // 启动定时刷新
            this.startAutoRefresh();
            
            showLoading(false);
            updateStatus('success', '系统运行正常');
            
            log('info', '实时交易量监控系统初始化完成');
        } catch (error) {
            handleError(error, '系统初始化');
            showLoading(false);
        }
    }

    /**
     * 初始化模拟数据
     */
    initMockData() {
        return {
            transaction: {
                totalData: this.generateTimeSeriesData(60, 30000, 50000),
                successData: this.generateTimeSeriesData(60, 29000, 49000),
                failData: this.generateTimeSeriesData(60, 500, 2000),
                currentVolume: 45200,
                currentSuccessRate: 98.5,
                updateTime: '2025-09-07 14:30:15'
            },
            failCodes: {
                failCodes: [
                    { retCode: 'Z00000', retDesc: '系统异常', failCount: 1250, failRate: 0.85 },
                    { retCode: '110022', retDesc: '网络超时', failCount: 890, failRate: 0.61 },
                    { retCode: '999999', retDesc: '未知错误', failCount: 567, failRate: 0.39 },
                    { retCode: '888888', retDesc: '数据库连接失败', failCount: 234, failRate: 0.16 },
                    { retCode: '777777', retDesc: '服务不可用', failCount: 123, failRate: 0.08 }
                ],
                timeData: this.generateTimeSeriesData(24, 0, 0, true),
                updateTime: '2025-09-07 14:30:15'
            }
        };
    }

    /**
     * 生成时间序列数据
     */
    generateTimeSeriesData(count, minValue, maxValue, isHourly = false, timeRangeMinutes = 360) {
        const data = [];
        const now = new Date();
        
        // 根据时间范围和数据点数量计算间隔
        let interval;
        if (isHourly) {
            interval = 3600000; // 1小时
        } else {
            // 根据时间范围动态计算间隔，确保数据点分布合理
            interval = (timeRangeMinutes * 60000) / count; // 总时间范围除以数据点数量
        }
        
        for (let i = count - 1; i >= 0; i--) {
            const time = new Date(now.getTime() - i * interval);
            let timeStr;
            
            if (isHourly) {
                timeStr = time.toLocaleString('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit' });
            } else {
                // 根据时间范围选择合适的时间格式
                if (timeRangeMinutes <= 60) {
                    // 1小时内，显示分钟
                    timeStr = time.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
                } else if (timeRangeMinutes <= 1440) {
                    // 24小时内，显示小时:分钟
                    timeStr = time.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
                } else {
                    // 超过24小时，显示月-日 时:分
                    timeStr = time.toLocaleString('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' });
                }
            }
            
            if (minValue === 0 && maxValue === 0) {
                data.push({ time: timeStr });
            } else {
                const value = Math.floor(Math.random() * (maxValue - minValue + 1)) + minValue;
                data.push({
                    time: timeStr,
                    value: value,
                    successRate: 90 + Math.random() * 10 // 调整为90%-100%之间，变化更明显
                });
            }
        }
        
        return data;
    }

    /**
     * 初始化时间显示
     */
    initTimeDisplay() {
        const updateTime = () => {
            $('#currentTime').text(getCurrentTimeString());
        };
        
        updateTime();
        setInterval(updateTime, 1000);
    }

    /**
     * 初始化事件监听
     */
    initEventListeners() {
        // 交易量监控查询条件
        $('#transactionTimeRange').on('change', debounce(async (e) => {
            await this.loadTransactionData();
        }, 300));
        
        $('#transactionCenterSelect').on('change', debounce(async (e) => {
            await this.loadTransactionData();
        }, 300));
        
        $('#transactionServicePlatSelect').on('change', debounce(async (e) => {
            await this.loadTransactionData();
        }, 300));
        
        $('#transactionChelCodeSelect').on('change', debounce(async (e) => {
            await this.loadTransactionData();
        }, 300));

        // 失败响应码查询条件
        $('#failCodeTimeRange').on('change', debounce(async (e) => {
            await this.loadFailCodeData();
        }, 300));
        
        $('#failCodeLimit').on('change', debounce(async (e) => {
            await this.loadFailCodeData();
        }, 300));
        
        $('#failCodeCenterSelect').on('change', debounce(async (e) => {
            await this.loadFailCodeData();
        }, 300));
        
        $('#failCodeServicePlatSelect').on('change', debounce(async (e) => {
            await this.loadFailCodeData();
        }, 300));

        // 页面可见性变化处理
        document.addEventListener('visibilitychange', () => {
            if (document.hidden) {
                this.pauseAutoRefresh();
            } else {
                this.resumeAutoRefresh();
            }
        });
    }

    /**
     * 检查API可用性
     */
    async checkApiAvailability() {
        try {
            const response = await $.ajax({
                url: '/api/tranvolume/health',
                method: 'GET',
                timeout: 3000
            });
            
            if (response && response.success) {
                this.isUsingMockData = false;
                log('info', 'API服务可用，使用真实数据');
                updateStatus('success', 'API连接正常');
            } else {
                throw new Error('API响应异常');
            }
        } catch (error) {
            this.isUsingMockData = true;
            log('warn', 'API服务不可用，使用模拟数据', error);
            updateStatus('error', '使用模拟数据');
        }
    }

    /**
     * 加载所有数据
     */
    async loadAllData() {
        const loadPromises = [
            this.loadTransactionData(),
            this.loadFailCodeData()
        ];

        try {
            await Promise.all(loadPromises);
            log('info', '所有交易监控数据加载完成');
        } catch (error) {
            handleError(error, '数据加载');
        }
    }

    /**
     * 加载交易量实时数据
     */
    async loadTransactionData() {
        try {
            const timeRange = parseInt($('#transactionTimeRange').val()) || 360;
            const center = $('#transactionCenterSelect').val();
            const servicePlat = $('#transactionServicePlatSelect').val();
            const chelCode = $('#transactionChelCodeSelect').val();
            
            let data;
            
            if (this.isUsingMockData) {
                data = this.mockData.transaction;
                // 根据时间范围调整数据
                const dataPoints = Math.floor(timeRange / 6); // 每6分钟一个数据点
                data = {
                    ...data,
                    totalData: this.generateTimeSeriesData(dataPoints, 30000, 50000, false, timeRange),
                    successData: this.generateTimeSeriesData(dataPoints, 29000, 49000, false, timeRange),
                    failData: this.generateTimeSeriesData(dataPoints, 500, 2000, false, timeRange)
                };
            } else {
                const params = { timeRange, center, servicePlat, chelCode };
                const response = await $.ajax({
                    url: this.config.apiEndpoints.transaction,
                    method: 'GET',
                    data: params,
                    timeout: 5000
                });
                data = response.data;
            }

            // 创建交易量综合图表
            createTransactionComprehensiveChart('transactionChart', data);
            
            // 更新统计数据
            $('#currentTotalVolume').text(formatNumber(data.currentVolume));
            $('#currentSuccessRate').text(formatPercent(data.currentSuccessRate));
            
            // 计算失败笔数
            const failCount = Math.floor(data.currentVolume * (100 - data.currentSuccessRate) / 100);
            $('#currentFailCount').text(formatNumber(failCount));

            log('info', '交易量数据更新完成');
        } catch (error) {
            handleError(error, '交易量数据加载');
        }
    }

    /**
     * 加载失败响应码数据
     */
    async loadFailCodeData() {
        try {
            const timeRange = parseInt($('#failCodeTimeRange').val()) || 360;
            const limit = parseInt($('#failCodeLimit').val()) || 10;
            const center = $('#failCodeCenterSelect').val();
            const servicePlat = $('#failCodeServicePlatSelect').val();
            
            let data;
            
            if (this.isUsingMockData) {
                data = this.mockData.failCodes;
                // 根据limit参数过滤
                data = {
                    ...data,
                    failCodes: data.failCodes.slice(0, limit),
                    timeData: this.generateTimeSeriesData(Math.floor(timeRange / 15), 0, 0, true, timeRange)
                };
            } else {
                const params = { timeRange, limit, center, servicePlat };
                const response = await $.ajax({
                    url: this.config.apiEndpoints.failCode,
                    method: 'GET',
                    data: params,
                    timeout: 5000
                });
                data = response.data;
            }

            createFailCodeTrendChart('failCodeChart', data);
            log('info', '失败响应码数据更新完成');
        } catch (error) {
            handleError(error, '失败响应码数据加载');
        }
    }

    /**
     * 启动自动刷新
     */
    startAutoRefresh() {
        // 交易量监控 - 1分钟刷新
        this.timers.transaction = setInterval(() => {
            this.loadTransactionData();
        }, this.config.refreshIntervals.transaction);

        // 失败响应码 - 1分钟刷新
        this.timers.failCode = setInterval(() => {
            this.loadFailCodeData();
        }, this.config.refreshIntervals.failCode);

        log('info', '实时交易量监控自动刷新已启动');
    }

    /**
     * 暂停自动刷新
     */
    pauseAutoRefresh() {
        Object.keys(this.timers).forEach(key => {
            if (this.timers[key]) {
                clearInterval(this.timers[key]);
                this.timers[key] = null;
            }
        });
        log('info', '实时交易量监控自动刷新已暂停');
    }

    /**
     * 恢复自动刷新
     */
    resumeAutoRefresh() {
        this.startAutoRefresh();
        log('info', '实时交易量监控自动刷新已恢复');
    }

    /**
     * 销毁应用
     */
    destroy() {
        this.pauseAutoRefresh();
        chartManager.disposeAll();
        log('info', '实时交易量监控应用已销毁');
    }
}

// 全局交易监控应用实例
let transactionMonitorApp;

// 文档加载完成后初始化应用
$(document).ready(function() {
    transactionMonitorApp = new TransactionMonitorApp();
});

// 页面卸载时清理资源
window.addEventListener('beforeunload', () => {
    if (transactionMonitorApp) {
        transactionMonitorApp.destroy();
    }
});